package com.distribution.common.web.auth;

import com.distribution.common.util.JwtUtils;
import com.distribution.common.web.response.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 *为了刷新token 令牌
 */

@RestController
public class AuthController {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * 刷新令牌
     * @return
     */
    @PostMapping("/refreshtoken")
    public ResponseEntity refreshToken(HttpServletRequest request){
        //从请求头中获取refreshToken
        String oldRefreshToken = request.getHeader(AuthConstant.REFRESH_TOKEN_HEADER);
        //校验refreshToken，如果令牌没有过期
        if (jwtUtils.isTokenExpired(oldRefreshToken)){
            return  new ResponseEntity(new ResponseResult(HttpStatus.BAD_REQUEST.value(),"刷新令牌已过期，请重新登录"),HttpStatus.OK);
        }

        //解析refreshToken
        String username = jwtUtils.getUsernameFromToken(oldRefreshToken);
        //生成新的accessToken
        String newAccessToken = jwtUtils.createToken(username);
        String newRefreshToken = jwtUtils.refreshToken(newAccessToken);

        Object obj  = LoginToken.builder().accessToken(newAccessToken).refreshToken(newRefreshToken).build();
        return  new ResponseEntity(new ResponseResult(HttpStatus.OK.value(),"令牌请求成功",obj),HttpStatus.OK);
    }

    @PostMapping("/login")
    public ResponseEntity login(String username,String password){
        // 生成一个包含账号密码的认证信息
        Authentication token = new UsernamePasswordAuthenticationToken(username, password);
        // AuthenticationManager校验这个认证信息，返回一个已认证的Authentication
        Authentication authentication = authenticationManager.authenticate(token);
        // 将返回的Authentication存到上下文中
        SecurityContextHolder.getContext().setAuthentication(authentication);

        return  new ResponseEntity(new ResponseResult(HttpStatus.OK.value(),"login success"),HttpStatus.OK);
    }
}
